import threading
import time
from queue import Queue

import requests

from tools.mytools import *

__file__ = 'multiZhihu.py'
__author__ = 'Jerry Liu'
__date__ = '2016-04-22'

SHARE_Q = Queue() # 构造一个不限制大小的的队列
_WORKER_THREAD_NUM = 2
_session = requests.session()

domain = 'https://www.zhihu.com/'
loginurl = 'http://www.zhihu.com/login/email'
followees = 'https://www.zhihu.com/people/%userid/followees'
username = '@qq.com'
pwd = ''

class MyQueueThread(threading.Thread):
    '''
    线程
    '''
    def __init__(self, func):
        super(MyQueueThread, self).__init__()
        self.func = func

    def run(self):
        self.func()


def getCaptcha():
    """
    获取验证码
    :return:
    """
    # 验证码
    t = str(int(time.time() * 1000))
    captcha_url = 'http://www.zhihu.com/captcha.gif?r' + t + '&type=login'
    captcha = _session.get(captcha_url, stream=True)
    f = open('d://爬虫/知乎壁验证码/captcha.gif', 'wb')
    for line in captcha.iter_content(10):
        f.write(line)
    f.close()

def doSignin():
    """
    登录
    :return:
    """
    getCaptcha()
    captcha = input('请输入验证码, ')
    # xsrf
    hbody = getBsByGet(_session, 'https://www.zhihu.com/#signin')
    xsrf = ((hbody.find_all('input', attrs={"name": "_xsrf"}))[0]).get('value')
    # 登录
    data = {'email': username, 'password': pwd, 'captcha': captcha, '_xsrf': xsrf}
    r = getJson(_session, loginurl, data)
    if r['r'] == 0:
        print('登录成功')
        getSetting()
    else:
        print('登录失败,请重试......', r['msg'])
        doSignin()


def getSetting():
    """
    设置
    :return:
    """
    # 查询我的userid
    profileHtml = getBsByGet(_session, 'https://www.zhihu.com/settings/profile')
    userid = profileHtml.find_all('input', attrs={'name': 'url_token'})[0].get('value')
    SHARE_Q.put(userid)

def getMyFollowees():
    """
    我关注的人
    :return:
    """
    userlist = []
    while not SHARE_Q.empty():
        userid = SHARE_Q.get()  # 获得任务
        print("Processing : ", userid)
        time.sleep(1)
        followeesUrl = followees.replace('%userid', userid)
        followeeshtml = getBsByGet(_session, followeesUrl)
        followeelist = followeeshtml.find_all('a', attrs={'class':'zg-link'})
        for i in range(len(followeelist)):
            followee = followeelist[i]
            fusername = followee.text
            fuserid = followee.get('data-tip')[4:]
            fdomain = followee.get('href')
            data = [userid, fuserid, fusername,fdomain]
            saveMySql(data)
            print(data)
            if fuserid not in userlist:
                userlist.append(fuserid)
                SHARE_Q.put(fuserid)

def main():
    threads = []
    doSignin()
    while True:
        cmd = input('请输入操作代码，1 我的关注人 2 关注我的人：')
        cmd = int(cmd)
        if cmd == 1:
            for i in range(_WORKER_THREAD_NUM):
                thread = MyQueueThread(getMyFollowees())
                thread.start()
                threads.append(thread)

            for thread in threads:
                thread.join()
        elif cmd == 2:
            pass
        else:
            print('命令错误，请重新输入。')
    else:
        print('退出')

if __name__ == '__main__':
    main()
